from django.contrib.auth.models import User, Group
from django.db import transaction
from rest_framework import status
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet, ModelViewSet
from utils.filters import MyPageNumberPagination
from utils.permissions import UserLoginPermissions, AdministratorsPermission
from .serializers import RegisterSerializer, LoginTokenObtainSerializer, GroupSerializer
from rest_framework_simplejwt.views import TokenObtainPairView


class RegisterGenericViewSet(GenericViewSet):
    queryset = User.objects.all()
    serializer_class = RegisterSerializer

    def create(self, request):

        # 校验用户名是否存在
        user = self.get_queryset().filter(username=request.data.get("username")).first()
        if user:
            return Response({
                "status": status.HTTP_409_CONFLICT,
                "msg": "该用户已存在，请换一个用户名进行注册",
            })
        # 校验数据是否正确
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        try:
            with transaction.atomic():
                # 创建用户
                user = User(
                    username=request.data.get('username'),
                    first_name='mq' + request.data.get('username'),
                    is_active=1
                )
                request.data['password'] = request.data.get('password')
                user.set_password(request.data.get('password'))
                user.save()
        except Exception as e:
            return Response({
                "status": status.HTTP_409_CONFLICT,
                "msg": "注册失败",
            })
        # 如果一切正常，返回成功响应
        return Response({
            'status': status.HTTP_201_CREATED,
            'msg': '注册成功，请前往登录页面登录'
        })


class LoginGenericViewSet(TokenObtainPairView):
    serializer_class = LoginTokenObtainSerializer

    def post(self, request, *args, **kwargs):
        # 校验用户信息，获取token
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        try:
            user = serializer.validated_data['user']
        except KeyError:
            return Response({
                "status": status.HTTP_404_NOT_FOUND,
                "msg": "该用户不存在或密码错误"
            })
        user_status = 0
        if user.is_superuser:
            user_status = 1
        response_data = {
            "status": status.HTTP_201_CREATED,
            "res_data": {
                "token": serializer.validated_data['access'],
                "username": user.first_name,
                "user_id": str(user.id),
                "status": user_status  # 用户身份
            }
        }
        return Response(response_data)


class GroupViewSet(ModelViewSet):
    queryset = Group.objects.all().order_by('id')
    serializer_class = GroupSerializer
    pagination_class = MyPageNumberPagination
    permission_classes = [UserLoginPermissions]  # 定义权限类只能用复数

    def get_queryset(self):
        if self.action in ['list', 'retrieve', 'search']:
            return Group.objects.all().order_by('id')
        return Group.objects.all()

    def get_permissions(self):
        permission_classes = [UserLoginPermissions]
        if self.action in ['create', 'update', 'destroy']:
            permission_classes.append(AdministratorsPermission)
        return [permission() for permission in permission_classes]
